package com.hliushi.learn.config;

import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.base.CoordinatorRegistryCenter;
import com.hliushi.learn.job.FileBackupJobBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author llhuang10
 * @date 2021/8/17 8:57
 */
@Configuration
public class ElasticJobConfig {

    @Resource
    private FileBackupJobBean fileBackupJobBean;

    @Resource
    private CoordinatorRegistryCenter registryCenter;


    /**
     * 任务启动
     *
     * @return SpringJobScheduler 基于Spring的作业启动器
     */
    @Bean(initMethod = "init")
    public SpringJobScheduler initSimpleElasticJob() {
        /**
         * bug点  cron表达式有问题
         * CronExpression '0/3 * * * * *' is invalid
         */
        SimpleJob job1 = fileBackupJobBean;
        // 创建SpringJobScheduler
        return new SpringJobScheduler(job1, registryCenter, createJobConfiguration(job1.getClass()
                , "0/3 * * * * ?", 4, "0=text,1=image,2=radio,3=vedio"));
    }

    /**
     * 配置任务详细信息
     *
     * @param jobClass               执行任务类
     * @param cron                   执行策略
     * @param shardingTotalCount     分片数量
     * @param shardingItemParameters 分片个性化参数
     * @return Lite作业配置
     */
    private LiteJobConfiguration createJobConfiguration(final Class<? extends SimpleJob> jobClass,
                                                        final String cron,
                                                        final int shardingTotalCount,
                                                        final String shardingItemParameters) {
        // JobCoreConfigurationBuilder
        // jobName = jobClass.getName() 全路径类名
        JobCoreConfiguration.Builder builder = JobCoreConfiguration.newBuilder(jobClass.getName(), cron, shardingTotalCount);
        // 设置shardingItemParameters
        if (StringUtils.isNotEmpty(shardingItemParameters)) {
            builder.shardingItemParameters(shardingItemParameters);
        }
        JobCoreConfiguration jobCoreConfiguration = builder.build();
        // 创建SIMPLE类型配置
        SimpleJobConfiguration simpleJobConfiguration = new SimpleJobConfiguration(jobCoreConfiguration, jobClass.getCanonicalName());

        // 定义Lite作业根配置
        return LiteJobConfiguration.newBuilder(simpleJobConfiguration).overwrite(true).build();
    }

}
